package com.person.MybatisSpring;

import java.util.HashMap;
import java.util.Map;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;

public class MybatisUtils {
	public static Map<Integer,SqlSession> sqlSession;  
    public static Map<Integer,Configuration> configuration;  
      
    static{  
        Map<String, SqlSessionFactoryBean> map = SpringUtils.getBeansOfType(SqlSessionFactoryBean.class);  
        sqlSession = new HashMap<Integer, SqlSession>();  
        configuration = new HashMap<Integer, Configuration>();  
        for (SqlSessionFactoryBean s : map.values()) {  
            int id = s.hashCode();  
            try {  
                SqlSession ss = new SqlSessionTemplate(s.getObject());  
                sqlSession.put(id, ss);  
                configuration.put(id, ss.getConfiguration());   
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
    }  
      
    /** 
     * 根据sqlId获取DatabaseId 
     * @param sqlId 
     * @return 
     */  
    public static int getDatabaseId(String sqlId){  
        for (int i : configuration.keySet()) {  
            Configuration c = configuration.get(i);  
            try {  
                //包含在try里，如果不加，找不到就抛出异常，终止循环  
                MappedStatement ms = c.getMappedStatement(sqlId);  
                if(null != ms){  
                    return i;  
                }  
            } catch (Exception e) {  
            }  
        }  
        return 0;  
    }  
    /** 
     * 根据sqlId取DatabaseId再返回SqlSession 
     * @param sqlId 
     * @return 
     */  
    public static SqlSession getSqlSession(String sqlId){  
        return sqlSession.get(getDatabaseId(sqlId));  
    }  
}
